<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      ref="crud"
      v-model="form"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @tree-load="treeLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.dept_delete" plain @click="handleDelete">删 除 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="scope" slot="menu">
        <el-button type="text" icon="el-icon-circle-plus-outline" size="small" @click.stop="handleAdd(scope.row, scope.index)"
          >新增子项
          <!-- v-if="userInfo.role_name.includes('admin')" -->
        </el-button>
      </template>
      <template slot-scope="{ row }" slot="deptCategory">
        <el-tag>{{ row.deptCategoryName }}</el-tag>
      </template>
      <template slot="principalNameForm">
        <el-input placeholder="请选择 负责人员" v-model="form.principalName" class="input-with-select" disabled>
          <el-button
            slot="append"
            icon="el-icon-circle-close"
            v-if="form.principalName"
            @click="
              form.principalName = '';
              form.principal = '';
            "
          ></el-button>
          <el-button slot="append" icon="el-icon-search" @click="openUserCommonModal()"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getLazyList, remove, update, add, getDept, getDeptTree } from '@/api/system/dept';
import { mapGetters } from 'vuex';
import website from '@/config/website';
import { getTableList } from '@/api/product/shift';
import trainingsubjectVue from '../product/trainingsubject.vue';
import { validateContacts } from '@/mixins/validateContacts.js';
import userConfig from '@/mixins/userConfig';
import userTableConfig from '@/components/user-table-config';
export default {
  name: 'SystemDept',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    let _this = this;
    return {
      pageCode: 'DEPT',
      form: {},
      defaults: {
        parentId: ''
      },
      selectionList: [],
      query: {},
      loading: true,
      parentId: 0,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      option: {
        height: 'calc(100vh - 280px)',
        calcHeight: 30,
        lazy: true,
        tip: false,
        // simplePage: true,
        searchShow: true,
        searchMenuSpan: 6,
        // tree: true,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        viewBtn: true,
        viewBtnText: '详情',
        viewText: '详情',
        menuWidth: 300,
        dialogClickModal: false,
        labelWidth: 180,
        dialogDrag: true,
        columnBtn: false,
        column: [
          {
            label: '名称',
            prop: 'deptName',
            search: true,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ],
            click: (val, form) => {}
          },
          {
            label: '所属租户',
            prop: 'tenantId',
            type: 'tree',
            dicUrl: '/api/blade-system/tenant/select',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: website.tenantMode,
            span: 24,
            props: {
              label: 'tenantName',
              value: 'tenantId'
            },
            hide: !website.tenantMode,
            search: website.tenantMode,
            rules: [
              {
                required: true,
                message: '请输入所属租户',
                trigger: 'click'
              }
            ]
          },
          {
            label: '全称',
            prop: 'fullName',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入全称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '上级机构',
            prop: 'parentId',
            dicData: [],
            type: 'tree',
            hide: true,
            value: '',
            disabled: false,
            props: {
              label: 'title',
              value: 'id'
            },
            rules: [
              {
                required: false,
                message: '请选择上级机构',
                trigger: 'click'
              }
            ]
          },
          {
            label: '类型',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=org_category',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            // dataType: "number",
            width: 120,
            prop: 'deptCategory',
            slot: true,
            rules: [
              {
                required: true,
                message: '请输入类型',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {
              if (val && parseInt(val) === 4) {
                this.form.fifoRequired = false;
                this.form.sequenceDefinitionId = '';
                this.form.sequenceDefinitionName = '';
                this.form.partCategories = '';
                // // 班组
                return {
                  shiftId: {
                    display: true,
                    hide: false
                  },
                  isWorkshop: {
                    disabled: true
                  },
                  fifoRequired: {
                    display: false
                  },
                  // lotRequired: {
                  //     display: true
                  // },
                  sequenceDefinitionName: {
                    display: false
                  },
                  partCategories: {
                    display: false
                  }
                };
              } else if (val && parseInt(val) === 2) {
                this.form.fifoRequired = false;
                this.form.sequenceDefinitionId = '';
                this.form.sequenceDefinitionName = '';
                this.form.partCategories = '';
                // 工厂
                return {
                  shiftId: {
                    display: false
                  },
                  isWorkshop: {
                    disabled: true
                  },
                  fifoRequired: {
                    display: false
                  },
                  // lotRequired: {
                  //     display: true
                  // },
                  sequenceDefinitionName: {
                    display: false
                  },
                  partCategories: {
                    display: false
                  }
                };
              } else if (val && parseInt(val) === 5) {
                // 库存中心
                return {
                  shiftId: {
                    display: false
                  },
                  fifoRequired: {
                    display: true
                  },
                  // lotRequired: {
                  //     display: true
                  // },
                  sequenceDefinitionName: {
                    display: true
                  },
                  partCategories: {
                    display: true
                  }
                };
              } else {
                this.form.fifoRequired = false;
                this.form.sequenceDefinitionId = '';
                this.form.sequenceDefinitionName = '';
                this.form.partCategories = '';
                return {
                  shiftId: {
                    display: false
                  },
                  fifoRequired: {
                    display: false
                  },
                  // lotRequired: {
                  //     display: true
                  // },
                  sequenceDefinitionName: {
                    display: false
                  },
                  partCategories: {
                    display: false
                  }
                };
              }
            },
            change({ value, column }) {
              _this.$nextTick(async () => {
                if (value && parseInt(value) === 4) {
                  // 获取班次数据
                  await _this.getShiftData();
                  const column = _this.findObject(_this.option.column, 'fifoRequired');
                  column.display = false;
                }
              });
            }
          },
          {
            label: '班次',
            type: 'select',
            dicData: [],
            props: {
              label: 'name',
              value: 'id'
            },
            // dataType: 'shiftId',
            width: 120,
            prop: 'shiftId',
            slot: true,
            display: true,
            hide: true,
            rules: [
              {
                required: true,
                message: '请输入班次',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '排序',
            prop: 'sort',
            align: 'right',
            width: 80,
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^[1-9]\d*$/g;
                  if (value && !reg.test(value)) {
                    callback(new Error('排序为数字，不能小于等于0并且是整数！'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '地址',
            prop: 'locationName',
            disabled: true,
            type: 'search',
            rules: [
              {
                required: true,
                message: '请选择地址',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLocationCommonModal();
            }
          },
          {
            label: '负责人',
            prop: 'principalName'
          },
          {
            label: '联系方式',
            prop: 'contacts',
            rules: [{ validator: validateContacts, trigger: 'blur' }]
          },
          {
            label: '成立日期',
            prop: 'registerDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            rules: [
              {
                required: true,
                message: '请选择成立日期',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '启用',
            prop: 'status',
            type: 'switch',
            value: 1,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            hide: true,
            type: 'textarea',
            minRows: 3,
            maxRows: 3
          },
          {
            label: '站点',
            prop: 'isSite',
            type: 'switch',
            display: false,
            hide: true,
            value: false,
            disabled: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择是不是站点',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {
              if (val && !form.isWorkshop) {
                return {
                  isWorkshop: {
                    disabled: true
                  }
                };
              } else if (!val && !form.isWorkshop) {
                this.form.accessCode = '';
                this.form.accessToken = '';
                return {
                  isWorkshop: {
                    disabled: false
                  }
                };
              }
            }
          },
          {
            label: '短码',
            prop: 'siteAbbr',
            hide: false,
            display: false
            // disabled: true
          },
          // {
          //     label: '边端唯一标识',
          //     prop: 'accessCode',
          //     display: false,
          //     rules: [
          //         {
          //             required: true,
          //             message: '请输入边端唯一标识',
          //             trigger: 'blur'
          //         }
          //     ]
          // },
          // {
          //     label: '边端token',
          //     prop: 'accessToken',
          //     display: false,
          //     rules: [
          //         {
          //             required: true,
          //             message: '请输入边端token',
          //             trigger: 'blur'
          //         }
          //     ]
          // },
          // {
          //     label: '库存中心',
          //     prop: 'isInventory',
          //     type: 'switch',
          //     value: false,
          //     hide: true,
          //     disabled: false,
          //     display: false,
          //     dicData: [
          //         {
          //             label: '否',
          //             value: false
          //         },
          //         {
          //             label: '是',
          //             value: true
          //         }
          //     ],
          //     rules: [
          //         {
          //             required: true,
          //             message: '请选择是不是库存中心',
          //             trigger: 'blur'
          //         }
          //     ],
          //     control: (val, form) => {

          //         if (val && !form.isSite && !form.isWorkshop) {
          //             return {
          //                 fifoRequired: {
          //                     display: true
          //                 },
          //                 // lotRequired: {
          //                 //     display: true
          //                 // },
          //                 sequenceDefinitionName: {
          //                     display: true
          //                 },
          //                 partCategories: {
          //                     display: true
          //                 },
          //                 isSite: {
          //                     disabled: true
          //                 },
          //                 isWorkshop: {
          //                     disabled: true
          //                 }
          //             };
          //         } else if (
          //             !val &&
          //             !form.isSite &&
          //             !form.isWorkshop
          //         ) {
          //             this.form.fifoRequired = false;
          //             this.form.lotRequired = false;
          //             this.form.sequenceDefinitionId = '';
          //             this.form.sequenceDefinitionName = '';
          //             this.form.partCategories = '';
          //             return {
          //                 fifoRequired: {
          //                     display: false
          //                 },
          //                 // lotRequired: {
          //                 //     display: false
          //                 // },
          //                 sequenceDefinitionName: {
          //                     display: false
          //                 },
          //                 partCategories: {
          //                     display: false
          //                 },
          //                 isSite: {
          //                     disabled: false
          //                 },
          //                 isWorkshop: {
          //                     disabled: false
          //                 }
          //             };
          //         }
          //     }
          // },
          {
            label: '管理先进先出',
            prop: 'fifoRequired',
            type: 'switch',
            display: true,
            hide: true,
            value: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          // {
          //     label: '管理批次',
          //     prop: 'lotRequired',
          //     type: 'switch',
          //     display: false,
          //     value: false,
          //     dicData: [
          //         {
          //             label: '否',
          //             value: false
          //         },
          //         {
          //             label: '是',
          //             value: true
          //         }
          //     ]
          // },
          {
            label: '该区域可存储物料类别',
            prop: 'partCategories',
            display: false,
            hide: true,
            props: {
              label: 'title',
              value: 'id'
            },
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            multiple: true,
            checkStrictly: true,
            rules: [
              {
                required: true,
                message: '请输入该区域可存储物料类别',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '序列号规则',
            prop: 'sequenceDefinitionName',
            disabled: true,
            type: 'search',
            display: false,
            hide: true,
            rules: [
              {
                required: true,
                message: '请选择序列号规则',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openSquenceModal();
            }
          },
          {
            label: '车间',
            prop: 'isWorkshop',
            type: 'switch',
            value: false,
            hide: true,
            display: false,
            disabled: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择是不是车间',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {}
          }
        ]
      },
      data: [],
      tableOption: {},
      modalName: '',
      timer: new Date().getTime(),
      isChildAdd: false
    };
  },

  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.dept_add, false),
        viewBtn: this.vaildData(this.permission.dept_view, false),
        delBtn: this.vaildData(this.permission.dept_delete, false),
        editBtn: this.vaildData(this.permission.dept_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    // 获取上级机构
    getOrgList() {
      const column = this.findObject(this.option.column, 'parentId');
      getDeptTree().then((res) => {
        column.dicData = res.data.data;
      });
    },
    getShiftData() {
      let params = {
        current: 1,
        size: 10000
      };
      getTableList(params).then((res) => {
        const column = this.findObject(this.option.column, 'shiftId');
        column.dicData = res.data.data.records;
      });
    },
    handleAdd(row) {
      this.parentId = row.id;
      this.isChildAdd = true;
      let dicData = [
        {
          id: row.id,
          deptName: row.deptName
        }
      ];
      console.log(' row', row);
      this.$set(this.defaults.parentId, 'dicData', dicData);
      this.$set(this.defaults.parentId, 'value', row.id);
      this.$set(this.defaults.parentId, 'disabled', true);
      this.$refs.crud.rowAdd();
    },
    rowSave(row, done, loading) {
      add(row).then(
        (res) => {
          // 获取新增数据的相关字段
          const data = res.data.data;
          row.id = data.id;
          row.deptCategoryName = data.deptCategoryName;
          row.tenantId = data.tenantId;
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.parentId = 0;
          this.onLoad(this.page);
          // 数据回调进行刷新
          done(row);
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.parentId = 0;
          this.onLoad(this.page);
          // 数据回调进行刷新
          done(row);
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row, index, done) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          // 数据回调进行刷新
          done(row);
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          // 刷新表格数据并重载
          this.data = [];
          this.parentId = 0;
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          // 表格数据重载
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    searchReset() {
      this.query = {};
      this.parentId = 0;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.parentId = '';
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    beforeOpen(done, type) {
      this.getOrgList();
      if (['edit', 'view'].includes(type)) {
        getDept(this.form.id).then((res) => {
          this.form = res.data.data;
          if (this.form.parentId === '0') {
            this.form.parentId = '';
          }
          this.form.deptCategory && (this.form.deptCategory = this.form.deptCategory + '');
        });
      } else {
        this.form = {};
        if (['add'].includes(type)) {
          if (!this.isChildAdd) {
            this.$set(this.defaults.parentId, 'dicData', []);
            this.$set(this.defaults.parentId, 'value', '');
            this.$set(this.defaults.parentId, 'disabled', false);
          }
          this.isChildAdd = false;
        }
      }
      done();
    },
    beforeClose(done) {
      this.parentId = '';
      this.$set(this.defaults.parentId, 'dicData', []);
      this.$set(this.defaults.parentId, 'value', '');
      this.$set(this.defaults.parentId, 'disabled', false);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getLazyList(this.parentId, Object.assign(params, this.query)).then((res) => {
        let data = res.data.data;
        this.data = this._forEach(data, (item) => {});
        this.loading = false;
        this.selectionClear();
      });
    },
    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      getLazyList(parentId).then((res) => {
        resolve(res.data.data);
      });
    },
    /**
     * 打开序列号模态框<>
     */
    openSquenceModal() {
      this.modalName = 'sequencedefinitionModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '序列号规则',
        url: '/api/mes-admin/sequencedefinition/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '规则名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入序列号规则名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入序列号规则编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '序列号规则',
            prop: 'sequencenoformat',
            labelslot: true,
            rules: [
              {
                required: true,
                message: '请输入序列号规则',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则位数',
            prop: 'charactersCount',
            rules: [
              {
                required: false,
                message: '请输入序列号规则位数',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    /**
     * 打开地址选择模态框
     */
    openLocationCommonModal() {
      this.modalName = 'locationModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择地址（双击进行选择）',
        url: '/api/mes-admin/location/page?status=0',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '地址名称',
            prop: 'name',
            search: true
          },
          {
            label: '国家',
            prop: 'countryName'
          },
          {
            label: '省份',
            prop: 'provinceName'
          },
          {
            label: '城市',
            prop: 'cityName'
          },
          {
            label: '详细地址1',
            prop: 'location1'
          },
          {
            label: '详细地址2',
            prop: 'location2'
          },
          {
            label: '详细地址3',
            prop: 'location3'
          },
          {
            label: '详细地址4',
            prop: 'location4'
          },
          {
            label: '邮编',
            prop: 'postCode'
          },
          {
            label: '经度',
            prop: 'latitude'
          },
          {
            label: '纬度',
            prop: 'longitude'
          }
        ]
      };
    },
    /**
     * 打开选择法人模态框
     */
    openUserCommonModal() {
      this.modalName = 'userModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择法人（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '登录账号',
            prop: 'account',
            search: true,
            display: false
          },
          {
            label: '所属租户',
            prop: 'tenantName',
            slot: true,
            display: false
          },
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            display: false
          },
          {
            label: '所属角色',
            prop: 'roleName',
            slot: true,
            display: false
          },
          {
            label: '所属部门',
            prop: 'deptName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            prop: 'userTypeName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=user_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dataType: 'number',
            search: true,
            hide: true,
            display: false,
            prop: 'userType',
            rules: [
              {
                required: true,
                message: '请选择用户平台',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    /**
     * 获取模态框选中数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'sequencedefinitionModal') {
        this.form['sequenceDefinitionId'] = rowData.id;
        this.form['sequenceDefinitionName'] = rowData.name;
      } else if (this.modalName === 'locationModal') {
        this.$set(this.form, 'locationId', this._get(rowData, 'id', ''));
        this.$set(this.form, 'locationName', this._get(rowData, 'name', ''));
      } else if (this.modalName === 'userModal') {
        this.form['principal'] = rowData.id;
        this.form['principalName'] = rowData.realName;
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style></style>
